import { useStore } from "@/stores";
import config from "@/static/ts/config";
import { getUnreadCount } from "@/static/ts/common";
import { handleGroupMessage, groupNotificationMessage } from "./groupChat";
import { handlePersonalMessage } from "./singleChat";

import i18n from "../i18n";

const RECONNECT_DELAY = 2000; // 重连间隔
const HEARTBEAT_INTERVAL = 10000; // 心跳包间隔
const HEARTBEAT_TIMEOUT = 13000; // 心跳超时

let store : any = null;
let wsInstance : UniApp.SocketTask | null = null;
let isConnected = false;
let isManuallyDisconnected = false;
let reconnectTimeout : any = null;
let reconnectAttempts = 0;
let heartbeatInterval : any = null;
let heartbeatTimeout : any = null;
let messageQueue : any = [];

const wsUrl = config.websocketUrl;

// 确认发送 sendStatus  0发送成功 1发送中 2发送失败
// Type=1个人 2群组
// Grade 1普通  2通知

// Grade 1普通
// Cmd 1文字 2图片 3视频  4红包

// Grade 2通知
// Type=1 Grade=2 1心跳包
// Cmd 1心跳包 2发送好友申请 3申请通过

// WebSocket 初始化
export function initializeWebSocket() {
	const userInfo = uni.getStorageSync("userInfo");
	if (!userInfo?.token) {
		console.warn("用户未登录或 token 不存在，无法初始化 WebSocket");
		return;
	}
	isManuallyDisconnected = false; // 重置手动断开标志
	store = useStore();
	connectWebSocket();
}

// WebSocket 连接逻辑
async function connectWebSocket() {
	if (isConnected) {
		console.warn("WebSocket 已连接，跳过重复连接");
		return;
	}

	const userInfo = uni.getStorageSync("userInfo");
	if (!userInfo?.token) {
		console.warn("用户未登录，无法建立 WebSocket 连接");
		return;
	}

	wsInstance = await uni.connectSocket({
		url: wsUrl,
		protocols: [userInfo.token],
		success: () => console.log("WebSocket 正在连接..."),
		fail: (e) => console.error("WebSocket 连接失败", e),
	});

	bindWebSocketEvents();
}

// 绑定 WebSocket 事件
function bindWebSocketEvents() {
	if (!wsInstance) return;

	wsInstance.onOpen(() => {
		console.log("WebSocket 连接已建立");

		isConnected = true;
		reconnectAttempts = 0;
		flushMessageQueue(); // 发送积压消息
		startHeartbeat(); // 启动心跳
	});

	wsInstance.onMessage(async (event) => handleWebSocketMessage(event));

	wsInstance.onClose(() => {
		console.warn("WebSocket 连接已关闭");
		handleWebSocketClose();
	});

	wsInstance.onError((error) => {
		console.error("WebSocket 错误", error);
		handleWebSocketClose();
	});
}

// 处理收到的 WebSocket 消息
async function handleWebSocketMessage(event : { data : string }) {
	try {
		const data = JSON.parse(event.data);
		const myUserInfo = uni.getStorageSync("userInfo");
		data.myUserId = myUserInfo.user_id;
		if (data.Id) {
			delete data.Id;
		}
		if (
			data.Grade === 2 &&
			data.Cmd === 1 &&
			data.Type === 1 &&
			data.Content === "pong"
		) {
			// 心跳包响应
			clearTimeout(heartbeatTimeout);
			return;
		}

		console.log("收到消息：", data);

		// 聊天消息
		if (data.Grade === 1) {
			store.db.saveData("unreadMessage", [
				{
					...data,
					id: data.Type == 1 ? data.Sender : data.GroupId,
					myUserId: uni.getStorageSync("userInfo").user_id
				},
			]);
			if (data.Type === 1) {
				await handlePersonalMessage(data);
			} else if (data.Type === 2) {
				if (data.myUserId == data.Sender.user_id) {
					console.log("自己给自己推送数据的业务，目前暂无");
					return;
				}
				await handleGroupMessage(data);
			}
		}
		// 通知消息
		else if (data.Grade === 2) {
			playVoice(3);

			if (data.Type === 1) {

				// 单聊通知
				// 暂无逻辑
			} else if (data.Type === 2) {
				await groupNotificationMessage(data);
			}
		}
		await store.updateLatestData(data);
		await getUnreadCount();
	} catch (error) {
		console.error("处理消息时出错：", error);
	}
}

// 发送消息
export function sendMessage(message : any) {
	if (isConnected && wsInstance) {
		wsInstance.send({
			data: JSON.stringify(message),
			success: () => console.log("消息发送成功", message),
			fail: (error) => console.error("消息发送失败", error),
		});
	} else {
		if (message?.type != 'push') {
			console.warn("WebSocket 未连接，消息加入队列", message);
			messageQueue.push(message);
		}

	}
}

// 发送积压消息
function flushMessageQueue() {
	while (messageQueue.length > 0) {
		const message = messageQueue.shift();
		if (message) sendMessage(message);
	}
}

// 心跳包逻辑
function startHeartbeat() {
	if (heartbeatInterval) return; // 防止重复启动
	heartbeatInterval = setInterval(sendHeartbeat, HEARTBEAT_INTERVAL);
}

function stopHeartbeat() {
	clearInterval(heartbeatInterval);
	heartbeatInterval = null;
}

function sendHeartbeat() {
	if (!isConnected || !wsInstance) return;

	wsInstance.send({
		data: JSON.stringify({ cmd: "heartbeat" }),
		success: () => {
			heartbeatTimeout = setTimeout(handleHeartbeatTimeout, HEARTBEAT_TIMEOUT);
		},
		fail: (error) => {
			console.error("心跳包发送失败", error);
			handleHeartbeatTimeout();
		},
	});
}

function handleHeartbeatTimeout() {
	console.warn("心跳超时，可能连接已断开");
	reconnectWebSocket();
}

// 处理 WebSocket 关闭
function handleWebSocketClose() {
	isConnected = false;
	stopHeartbeat();
	if (!isManuallyDisconnected) reconnectWebSocket();
}

// 重连逻辑
function reconnectWebSocket() {
	if (isManuallyDisconnected) {
		console.log("手动断开，停止重连");
		return;
	}

	if (reconnectTimeout) clearTimeout(reconnectTimeout);
	reconnectTimeout = setTimeout(() => {
		console.log("尝试重连 WebSocket...");
		reconnectAttempts++;
		connectWebSocket();
	}, RECONNECT_DELAY);
}

// 手动断开 WebSocket
export function disconnectWebSocket() {
	isManuallyDisconnected = true;
	stopHeartbeat();
	wsInstance?.close({
		code: 1000, // 正常关闭状态码
		reason: "Manual disconnect", // 关闭原因
		success: () => console.log("WebSocket 连接已手动关闭"),
		fail: (error) => console.error("关闭 WebSocket 时出错", error),
	});
	wsInstance = null;
	isConnected = false;
}